import hashlib
import logging
import os
import sys

from BTL.bencode import bencode, bdecode
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from model import *

class GetTorrent(webapp.RequestHandler):
    def get(self, httpSeedPath, info_hash):
        t = Torrent.get_by_hash(info_hash)
        if t is None:
            # We dunno about this torrent.
            self.error(404)
        torrent = bdecode(t.bencoded_data)

        dl_name = torrent['info']['name']+".torrent"
        self.response.headers["Content-Type"] = "application/x-bittorrent"
        self.response.headers.add_header('Content-Disposition', 'attachment', filename=dl_name)

        announce_url = "http://"+os.environ['HTTP_HOST']+"/announce"
        seed_hoffman_url = "http://"+os.environ['HTTP_HOST']+httpSeedPath+"/hoffman"
        seed_getright_url = "http://"+os.environ['HTTP_HOST']+httpSeedPath+"/"+info_hash+"/"

        torrent['created by'] = 'http://code.google.com/p/torrent-server/'

        def add_or_insert(torrent, key, value):
            if not key in torrent:
                torrent[key] = [ value ]
            else:
                if not isinstance(torrent[key], list):
                    torrent[key] = [ torrent[key] ]
                if not value in torrent[key]:
                    torrent[key].append(value)

        # Add to the announce, and to the url-list, and httpseeds metainfo if we're
        # not already:
        torrent['announce'] = announce_url
        # maybe someday: add ourselves into the nested multitracker announce lists...
        if 'announce-list' in torrent: del torrent['announce-list']

        add_or_insert(torrent, 'httpseeds', seed_hoffman_url)
        add_or_insert(torrent, 'url-list', seed_getright_url)

        new_torrent_data = bencode(torrent)
        self.response.out.write(new_torrent_data)


application = webapp.WSGIApplication(
    [
      # Get .torrent file via GET requests to /seed/(infohash).torrent
      (r'(/seed)/(\w{40})\.torrent', GetTorrent),
    ],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
